package com.runing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runing.config.ResponseWrapper;
import com.runing.entity.*;
import com.runing.mapper.*;
import com.runing.service.RResultService;
import com.runing.service.RStatisticService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lel
 * @since 2021-03-11
 */
@Service
public class RStatisticServiceImpl extends ServiceImpl<RStatisticMapper, RStatistic> implements RStatisticService {

    @Autowired
    RStatisticMapper rStatisticMapper;
    @Autowired
    RWeekMapper weekMapper;
    @Autowired
    RInfoMapper infoMapper;
    @Autowired
    RRuleMapper ruleMapper;
    @Autowired
    RStudentMapper studentMapper;
    @Autowired
    RResultServiceImpl resultService;
    @Autowired
    RInfoMapper rInfoMapper;
    @Autowired
    CanrunServiceImpl canrunService;
    @Autowired
    ViolationMapper violationMapper;

    public ResponseWrapper runRecord(Integer sid ,Integer wid){
        QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
        statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
        List<RStatistic> rStatisticList = rStatisticMapper.selectList(statisticQueryWrapper);
        if (rStatisticList.size() == 0){
            return ResponseWrapper.markCustom(false,200,"暂无该用户的跑步记录",null);
        }else {
            RWeek week = weekMapper.selectById(wid);
            QueryWrapper<RInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("sid",sid).eq("seid",week.getSeid());
            RInfo info = infoMapper.selectOne(infoQueryWrapper);
            if (info == null){
                return ResponseWrapper.markCustom(false,200,"暂无该用户的信息",null);
            }else {
                ResponseWrapper wrapper = ResponseWrapper.markSuccess(rStatisticList);
                wrapper.getData().put("RunRecord",rStatisticList);
                wrapper.getData().put("snt",info.getSnt());
                wrapper.getData().put("sresult",info.getSresult());
                wrapper.getData().put("allmilsage",info.getAllmilsage());
                return wrapper;
            }

        }

    }

    public ResponseWrapper inTime(){
        Boolean canrun = canrunService.isCanrun();
        if (canrun){
            int hours =new Date().getHours();
            int Mins =new Date().getMinutes();
            int now = 0;
            if (Mins < 10){
                 now = Integer.valueOf(hours +"0"+ Mins);
            }else {
                 now = Integer.valueOf(String.valueOf(hours)+ Mins);
            }
            RRule rule = ruleMapper.selectById(1);
            RRule rules = ruleMapper.selectById(2);
            String stime =rule.getStarttime();
            String etime = rule.getEndtime();
            String starttime = rules.getStarttime();
            String endtime = rules.getEndtime();
            int startime = Integer.valueOf(stime.substring(0,2)+stime.substring(3,5));
            int ed = Integer.valueOf(etime.substring(0,2)+etime.substring(3,5));
            int sttime = Integer.valueOf(starttime.substring(0,2)+starttime.substring(3,5));
            int etimes = Integer.valueOf(endtime.substring(0,2)+endtime.substring(3,5));
            Boolean ruleOne = now >= startime && now < ed;
            Boolean ruleTwo = now >= sttime && now < etimes;
            if (ruleOne == false && ruleTwo == false){
                return ResponseWrapper.markCustom(false,500,"未到规定时间",null);
            }else {
                return ResponseWrapper.markCustom(true,200,"在规定时间内",null);
            }
        }else {
            return ResponseWrapper.markCustom(false,500,"服务器正在维护不能跑步",null);
        }

    }
    public Boolean check(Integer sid){
        QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
        statisticQueryWrapper.eq("sid",sid).orderByDesc("stid").last("limit 1");
        RStatistic statistic = rStatisticMapper.selectOne(statisticQueryWrapper);
        if (statistic ==null){
            return true;
        }else {
            String datetime = new SimpleDateFormat("yyMMddHHmm").format(statistic.getSttime().getTime());
            Date date = new Date();
            String nowtime = new SimpleDateFormat("yyMMddHHmm").format(date.getTime());
            Integer result = Integer.parseInt(nowtime) - Integer.parseInt(datetime);
            Boolean check;
            check = result >= 10;
            return check;
        }

    }
    public ResponseWrapper addStatisic(String latitude,String longitude,String ssid,RStatistic rStatistic){
        RStudent student = studentMapper.selectById(rStatistic.getSid());
        int mil = Integer.valueOf(rStatistic.getMileage());
        Boolean HasWid = rStatistic.getWid() != null;
        String sex = student.getSex();
        Boolean sdelete = student.getSdelete();
        Boolean hasLas = latitude == null || longitude == null;
        if (sdelete == false ){
            if (ssid == null){
                RStudent rStudent = new RStudent();
                rStudent.setSid(rStatistic.getSid());
                rStudent.setSdelete(true);
                studentMapper.updateById(rStudent);
                Violation violation = new Violation();
                violation.setLatitude(latitude);
                violation.setLongitude(longitude);
                violation.setSid(rStatistic.getSid());
                violation.setSname(student.getSname());
                violationMapper.insert(violation);
                return ResponseWrapper.markCustom(false,500,"你存在违规行为，账号已封禁",null);
            }else {
                if (Integer.valueOf(rStatistic.getMileage()) >= 2500){
                    Boolean canrun = canrunService.isCanrun();
                    if (canrun){
                        if (HasWid){
                            if (inTime().getCode() == 200){
                                if (check(rStatistic.getSid())){
                                    int counts = weekCount(rStatistic.getSid(),rStatistic.getWid());
                                    QueryWrapper<RRule> ruleQueryWrapper = new QueryWrapper<>();
                                    int uid = 0;
                                    if (sex.equals("女")){
                                        uid = 3;
                                    }else {
                                        uid = 1;
                                    }
                                    ruleQueryWrapper.eq("sex",sex).eq("uid",uid);
                                    RRule rule = ruleMapper.selectOne(ruleQueryWrapper);
                                    if (counts < rule.getRweek()){
                                        int milrule = (int) (new BigDecimal(rule.getRkm()).doubleValue()*1000);
                                        int times = Integer.valueOf(rStatistic.getRuntime().substring(3,5));
                                        if (10 <= times && times <=45 ){
                                            if (mil >= milrule){
                                                if (times<=15 && mil > 5000){
                                                    rStatistic.setMileage(String.valueOf(Integer.valueOf((int) (mil*0.7))));
                                                }
                                                int result = rStatisticMapper.insert(rStatistic);
                                                if (result == 1){
                                                    QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
                                                    statisticQueryWrapper.eq("sid",rStatistic.getSid());
                                                    int count = rStatisticMapper.selectCount(statisticQueryWrapper);
                                                    int srun = 0;
                                                    List<RResult> resultList = resultService.getResult();
                                                    int rReult1 = Integer.valueOf(resultList.get(0).getRresult());
                                                    int minrlt1 = Integer.valueOf(resultList.get(0).getMinresult());
                                                    int rReult2 = Integer.valueOf(resultList.get(1).getRresult());
                                                    int minrlt2 = Integer.valueOf(resultList.get(1).getMinresult());
                                                    int rReult3 = Integer.valueOf(resultList.get(2).getRresult());
                                                    int minrlt3 = Integer.valueOf(resultList.get(2).getMinresult());
                                                    int rReult4 = Integer.valueOf(resultList.get(3).getRresult());
                                                    int minrlt4 = Integer.valueOf(resultList.get(3).getMinresult());
                                                    int rReult5 = Integer.valueOf(resultList.get(4).getRresult());
                                                    int minrlt5 = Integer.valueOf(resultList.get(4).getMinresult());
                                                    int rReult6 = Integer.valueOf(resultList.get(5).getRresult());
                                                    int minrlt6 = Integer.valueOf(resultList.get(5).getMinresult());
                                                    if(rReult2 > count && count >=rReult1){
                                                        srun = minrlt1;
                                                    }
                                                    if(rReult3 > count && count >=rReult2){
                                                        srun = minrlt2;
                                                    }
                                                    if(rReult4 > count && count >=rReult3){
                                                        srun = minrlt3;
                                                    }
                                                    if(rReult5 > count && count >=rReult4){
                                                        srun = minrlt4;
                                                    }
                                                    if(rReult6 > count && count >=rReult5){
                                                        srun = minrlt5;
                                                    }
                                                    if(count >=rReult6){
                                                        srun = minrlt6;
                                                    }
                                                    RStudent rStudent = new RStudent();
                                                    rStudent.setSid(rStatistic.getSid());
                                                    rStudent.setSrun(String.valueOf(srun));
                                                    studentMapper.updateById(rStudent);
                                                    int sresult = (int) (srun * 0.2+Integer.valueOf(student.getInclass()) *0.6 +Integer.valueOf(student.getSpe())*0.2);
                                                    RWeek week =weekMapper.selectById(rStatistic.getWid());
                                                    QueryWrapper<RInfo> queryWrapper = new QueryWrapper<>();
                                                    queryWrapper.eq("sid",rStatistic.getSid()).eq("seid",week.getSeid());
                                                    RInfo rInfo = rInfoMapper.selectOne(queryWrapper);
                                                    if (rInfo == null){
                                                        RInfo rInfos = new RInfo();
                                                        rInfos.setSid(rStatistic.getSid());
                                                        rInfos.setSeid(week.getSeid());
                                                        rInfos.setSresult(String.valueOf(sresult));
                                                        rInfos.setSnt(count);
                                                        rInfos.setAllmilsage(mil);
                                                        rInfoMapper.insert(rInfos);
                                                    }else {
                                                        RInfo info = new RInfo();
                                                        info.setIId(rInfo.getIId());
                                                        info.setSid(rInfo.getSid());
                                                        info.setSid(rInfo.getSid());
                                                        info.setSresult(String.valueOf(sresult));
                                                        info.setSnt(count);
                                                        info.setAllmilsage(rInfo.getAllmilsage()+mil);
                                                        rInfoMapper.updateById(info);
                                                    }
                                                    return ResponseWrapper.markSuccess(null);
                                                }else {
                                                    return ResponseWrapper.markError();
                                                }
                                            }else {
                                                return ResponseWrapper.markCustom(false,500,"跑步距离不够",null);
                                            }
                                        }
                                        else {
                                            return ResponseWrapper.markCustom(false,500,"时间过短或过长",null);
                                        }
                                    }else {
                                        return ResponseWrapper.markCustom(false,500,"本周跑步次数已达上限",null);
                                    }
                                }else {
//                                            RStudent rStudent = new RStudent();
//                                            rStudent.setSid(rStatistic.getSid());
//                                            rStudent.setSdelete(true);
//                                            studentMapper.updateById(rStudent);
//                                            Violation violation = new Violation();
//                                            violation.setLatitude(latitude);
//                                            violation.setLongitude(longitude);
//                                            violation.setSid(rStatistic.getSid());
//                                            violation.setSname(student.getSname());
//                                            violation.setSsid(ssid);
//                                            violationMapper.insert(violation);
                                    return ResponseWrapper.markCustom(false,500,"请不要多次提交",null);
                                }
                            }else {
                                return ResponseWrapper.markCustom(false,500,"不在规定时间",null);
                            }
                        }else {
                            return ResponseWrapper.markCustom(false,500,"数据获取失败，请联系开发人员",null);
                        }

                    }else {
                        return ResponseWrapper.markCustom(false,500,"服务器正在维护，请晚点上传数据",null);
                    }
                }else {
                    return ResponseWrapper.markCustom(false,500,"跑步距离过短",null);
                }
            }
        }else {
            return  ResponseWrapper.markCustom(false,500,"你的账号已封禁，不能进行该操作",null);
        }
    }


    public List<RStatistic> nowWeekRStatistic(Integer sid ,Integer wid){
        QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
        statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
        List<RStatistic> rStatisticList = rStatisticMapper.selectList(statisticQueryWrapper);
        return rStatisticList;
    }

    public ResponseWrapper nowRSatistic(Integer sid ,Integer wid){
        List<RStatistic> rStatistics = nowWeekRStatistic(sid,wid);
            List<RResult> resultList = resultService.getResult();
            RWeek week = weekMapper.selectById(wid);
            QueryWrapper<RInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("sid",sid).eq("seid",week.getSeid());
            RInfo rInfo = infoMapper.selectOne(infoQueryWrapper);
            RStudent student = studentMapper.selectById(sid);
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(student);
            List<RStatistic> statisticList = new ArrayList<>();
            for (RStatistic rStatistic : rStatistics){
              RStatistic statistic =  new RStatistic();
                String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                Calendar cal = Calendar.getInstance();
                cal.setTime(rStatistic.getSttime());
                int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                if (w < 0)
                    w = 0;
                statistic.setStid(rStatistic.getStid());
                statistic.setSid(rStatistic.getSid());
                statistic.setWid(rStatistic.getWid());
                statistic.setMileage(rStatistic.getMileage());
                statistic.setRuntime(rStatistic.getRuntime());
                statistic.setSttime(rStatistic.getSttime());
                statistic.setWeekDays(weekDays[w]);
                statisticList.add(statistic);
            }
            wrapper.getData().put("runStatistic",statisticList);
            int res = 0;
            int rem = 0;
            if (rInfo == null){
                res = 0;
                rem = 0;
            }else {
                res = rInfo.getSnt();
                rem = rInfo.getAllmilsage();
            }
            wrapper.getData().put("snt",res);
            wrapper.getData().put("ALlMileage",rem);
            wrapper.getData().put("srun",student.getSrun());
            wrapper.getData().put("minresult",Integer.valueOf(resultList.get(5).getMinresult()));
            return wrapper;

    }

    public ResponseWrapper getStatisticByClid(Integer sid,Integer seid,Integer pageSize,Integer pageNum){
        QueryWrapper<RWeek> weekQueryWrapper = new QueryWrapper<>();
        weekQueryWrapper.eq("seid",seid);
        List<RWeek> weekList = weekMapper.selectList(weekQueryWrapper);
        if (weekList.size() == 0){
            return ResponseWrapper.markCustom(false,200,"学期错误",null);
        }else {
            List widlist = new ArrayList();
            for (RWeek week: weekList){
                widlist.add(week.getWid());
            }
            QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
            statisticQueryWrapper.eq("sid",sid).in("wid",widlist).orderByDesc("wid");
            Page<RStatistic> page = new Page<>(pageNum,pageSize);
            IPage<RStatistic> iPage =  rStatisticMapper.selectPage(page,statisticQueryWrapper);
            List list = iPage.getRecords();
            ResponseWrapper wrapper = new ResponseWrapper().markSuccess(list);
            wrapper.getData().put("data",list);
            wrapper.getData().put("total",iPage.getTotal());
            wrapper.getData().put("pageSize",iPage.getSize());
            wrapper.getData().put("pageNum",iPage.getPages());
            return wrapper;
        }

    }
    public ResponseWrapper getStatistic(Integer sid,Integer seid,Integer pageSize,Integer pageNum){
        Page<Map> page = new Page<>(pageNum,pageSize);
        IPage<Map> iPage = rStatisticMapper.findstatisByClid(page,sid,seid);
        List<Map> list = iPage.getRecords();
        ResponseWrapper wrapper = ResponseWrapper.markSuccess(list);
        wrapper.getData().put("data",list);
        wrapper.getData().put("total",iPage.getTotal());
        wrapper.getData().put("pageSize",iPage.getSize());
        wrapper.getData().put("pageNum",iPage.getCurrent());
        return wrapper;
    }

    public ResponseWrapper getSta(Integer clid,Integer wid){
        if (clid != null && wid != null){
            Integer allboy = 0;
            Integer allgril = 0,g0 =0,g1 = 0,g2 = 0,b0 = 0,b1 = 0,b2 = 0;
            QueryWrapper<RStudent> boyWrapper = new QueryWrapper<>();
            boyWrapper.eq("clid",clid).eq("sex","男");
            List<RStudent> boylist = studentMapper.selectList(boyWrapper);
            List<Integer> boycount = new ArrayList();
            for(RStudent boys : boylist){
                boycount.add(boys.getSid());
            }
            for (Integer sid : boycount){
                QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
                statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
                int cot = rStatisticMapper.selectCount(statisticQueryWrapper);
                if (cot == 2){
                    b2+=1;
                }
                if (cot == 1){
                    b1+=1;
                }
            }
            allboy = boylist.size();
            b0 = allboy - b2 -b1;
            QueryWrapper<RStudent> girlWrapper = new QueryWrapper<>();
            girlWrapper.eq("clid",clid).eq("sex","女");
            List<RStudent> girllist = studentMapper.selectList(girlWrapper);
            List<Integer> girlcount = new ArrayList();
            for(RStudent girl : girllist){
                girlcount.add(girl.getSid());
            }
            for (Integer sid : girlcount){
                QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
                statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
                int cot = rStatisticMapper.selectCount(statisticQueryWrapper);
                if (cot == 2){
                    g2+=1;
                }
                if (cot == 1){
                    g1+=1;
                }
            }
            allgril = girllist.size();
            g0 = allgril - g2 -g1;
            //转化为百分数
            DecimalFormat decimalFormat = new DecimalFormat("#0.##%");
            String boyZeroTimes = decimalFormat.format((double)b0 / allboy);
            String boyOnce = decimalFormat.format((double)b1 / allboy);
            String boyTwice = decimalFormat.format((double)b2 / allboy);
            String girlZeroTimes = decimalFormat.format((double)g0 / allgril);
            String girlOnce = decimalFormat.format((double)g1 / allgril);
            String girlTwice = decimalFormat.format((double)g2 / allgril);
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(allboy);
            wrapper.getData().put("girlOnce",girlOnce);
            wrapper.getData().put("girlTwice",girlTwice);
            wrapper.getData().put("girlZeroTimes",girlZeroTimes);
            wrapper.getData().put("g0",g0);
            wrapper.getData().put("g1",g1);
            wrapper.getData().put("g2",g2);
            wrapper.getData().put("allgril",allgril);
            wrapper.getData().put("boyZeroTimes",boyZeroTimes);
            wrapper.getData().put("boyOnce",boyOnce);
            wrapper.getData().put("boyTwice",boyTwice);
            wrapper.getData().put("b2",b2);
            wrapper.getData().put("b1",b1);
            wrapper.getData().put("b0",b0);
            wrapper.getData().put("allboy",allboy);
            return wrapper;
        }else {
            return ResponseWrapper.markCustom(false,400,"cid,wid不能为空",null);
        }
    }

    public ResponseWrapper nowWeekSta(Integer sid,Integer wid){
        if (sid == null || wid == null){
            return ResponseWrapper.markCustom(false,400,"sid或者wid为空",null);
        }else {
            RStudent student = studentMapper.selectById(sid);
            String sex = student.getSex();
            QueryWrapper<RRule> ruleQueryWrapper = new QueryWrapper<>();
            ruleQueryWrapper.eq("sex",sex).last("limit 1");
            RRule rule = ruleMapper.selectOne(ruleQueryWrapper);
            QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
            statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
            int count = rStatisticMapper.selectCount(statisticQueryWrapper);
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(rule);
            wrapper.getData().put("rkm",rule.getRkm());
            wrapper.getData().put("rweek",rule.getRweek());
            wrapper.getData().put("count",count);
            return wrapper;
        }
    }

    public Integer weekCount(Integer sid,Integer wid){
        QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
        statisticQueryWrapper.eq("sid",sid).eq("wid",wid);
        int count = rStatisticMapper.selectCount(statisticQueryWrapper);
        return count;
    }

}
